<template>
    <div>
        <div>
            <el-config-provider :locale="zhCn"> <!--《:locale="zhCn 》设置语言-->

                <el-scrollbar height="70vh">
                    <!-- 考勤打卡 -->
                    <el-row :gutter="24">
                        <el-col :span="24">
                            <div class="grid-content ep-bg-purple-light" style="padding: 15px 0;">
                                <el-form-item label="考勤打卡" label-position="top"
                                    :style="{ fontSize: '15px', fontWeight: 'bold', borderBottom: '1px dashed #e4e7ed' }">
                                    <div class="progress-bar">
                                        <div class="progress"></div>
                                    </div>
                                </el-form-item>

                            </div>
                        </el-col>

                        <el-col :span="12">
                            <!-- {{ attendanceRule }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="姓名" label-position="top"
                                    required>
                                    <el-input v-model="user.employeeName" style="/*width: 354px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <!-- {{ form }} -->
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="所在部门" label-position="top"
                                    required>
                                    <el-input v-model="user.department.deptName" style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <!--  -->
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="日期" label-position="top">
                                    <el-input v-model="form.recordDate" style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="归属考勤周期"
                                    label-position="top">
                                    <el-input v-model="form.attendanceCycle" style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="上班要求时间"
                                    label-position="top">
                                    <el-input v-model="form.workStartTime" style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="下班要求时间"
                                    label-position="top">
                                    <el-input v-model="form.workEndTime" style="/*width: 260px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="打卡时间" label-position="top"
                                    required>
                                    <el-input v-model="form.clockInTime" style="/*width: 354px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="定位" label-position="top"
                                    required>
                                    <span style="font-size: 12px;">限制了打卡范围，定位在公司附近才生效。</span>
                                    <el-input v-model="form.locationStatus" style="/*width: 354px;*/" disabled />
                                    <el-button @click="getLocation" :loading="locationLoading" size="small"
                                        style="margin-top: 5px;">
                                        {{ locationLoading ? '定位中...' : '获取位置' }}
                                    </el-button>
                                </el-form-item>
                            </div>
                        </el-col>

                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light"><el-form-item label="打卡状态" label-position="top"
                                    required>
                                    <el-input v-model="form.clockInStatus" style="/*width: 354px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>
                        <el-col :span="12">
                            <div class="grid-content ep-bg-purple-light">
                                <!-- 上午打卡时显示迟到分钟数 -->
                                <el-form-item v-if="showLateMinutes" label="迟到分钟数" label-position="top">
                                    <el-input v-model="form.lateMinutes" style="/*width: 354px;*/" disabled />
                                </el-form-item>
                                <!-- 下午打卡时显示早退分钟数 -->
                                <el-form-item v-if="showEarlyMinutes" label="早退分钟数" label-position="top">
                                    <el-input v-model="form.earlyMinutes" style="/*width: 354px;*/" disabled />
                                </el-form-item>
                            </div>
                        </el-col>

                        <div class="bottom-submit-bar">
                            <el-button type="primary" @click="handleClockIn"
                                :disabled="form.isClockInDisabled || !form.isInLocationRange">打卡</el-button>
                            <!-- <el-button>保存草稿</el-button> -->
                        </div>

                    </el-row>
                </el-scrollbar>

            </el-config-provider>
        </div>
    </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import request from '@/api/request';
import zhCn from 'element-plus/es/locale/lang/zh-cn'
import { ElMessage, ElMessageBox } from 'element-plus'
import router from '@/router';

// 获取session中的用户信息 - 需要解析JSON字符串
let user = JSON.parse(sessionStorage.getItem('user') || '{}');

const locationLoading = ref(false);

const form = reactive({
    recordDate: '',
    attendanceCycle: '',
    workStartTime: '',
    workEndTime: '',
    clockInTime: '',
    clockInStatus: '',
    lateMinutes: '',
    earlyMinutes: '',
    isClockInDisabled: false,
    locationStatus: '未获取位置信息',
    isInLocationRange: false,
    // 公司位置坐标 
    companyLocation: {
        latitude: 27.830385,   // 纬度
        longitude: 113.166869,  // 经度
        address: '公司地址' // 添加地址字段
    },
    // 允许的打卡范围(单位：米)
    allowedRange: 1000,
    // 从后端获取的考勤规则
    attendanceRule: {}
});

// 计算两点之间的距离 (使用 Haversine 公式)
const calculateDistance = (lat1, lon1, lat2, lon2) => {
    const R = 6371e3; // 地球半径(米)
    const φ1 = lat1 * Math.PI / 180; // φ, λ in radians
    const φ2 = lat2 * Math.PI / 180;
    const Δφ = (lat2 - lat1) * Math.PI / 180;
    const Δλ = (lon2 - lon1) * Math.PI / 180;

    const a = Math.sin(Δφ / 2) * Math.sin(Δφ / 2) +
        Math.cos(φ1) * Math.cos(φ2) *
        Math.sin(Δλ / 2) * Math.sin(Δλ / 2);
    const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1 - a));

    return R * c; // 距离(米)
};

// 逆地理编码 - 将经纬度转换为地址
const reverseGeocode = async (longitude, latitude) => {
    const API_KEY = 'c5634c2ef699342830e81bfd7b894122';
    const url = `https://restapi.amap.com/v3/geocode/regeo?key=${API_KEY}&location=${longitude},${latitude}`;

    try {
        const response = await fetch(url);
        const data = await response.json();

        if (data.status === '1' && data.regeocode) {
            // 返回格式化地址
            return data.regeocode.formatted_address;
        } else {
            return `经纬度: ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
        }
    } catch (error) {
        console.error('逆地理编码失败:', error);
        return `经纬度: ${latitude.toFixed(6)}, ${longitude.toFixed(6)}`;
    }
};

// 使用高德地图API获取当前位置
const getLocation = () => {
    // 显示加载状态
    locationLoading.value = true;
    form.locationStatus = '定位中...';

    // 加载高德地图API
    const script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = 'https://webapi.amap.com/maps?v=1.4.15&key=c5634c2ef699342830e81bfd7b894122';
    script.onerror = () => {
        locationLoading.value = false;
        form.locationStatus = '地图API加载失败';
        ElMessage.error('地图API加载失败');
    };
    script.onload = () => {
        // API加载成功后获取位置
        if (window.AMap) {
            window.AMap.plugin('AMap.Geolocation', () => {
                const geolocation = new window.AMap.Geolocation({
                    enableHighAccuracy: true, // 是否使用高精度定位
                    timeout: 10000,          // 超过10秒后停止定位
                    maximumAge: 60000,       // 定位结果缓存时间
                    convert: true,           // 自动偏移坐标
                    showButton: false,       // 不显示定位按钮
                    showMarker: false,       // 不显示定位点
                    showCircle: false        // 不显示定位圆圈
                });

                geolocation.getCurrentPosition((status, result) => {
                    locationLoading.value = false;

                    if (status === 'complete') {
                        const { position } = result;
                        const { lng, lat } = position;

                        // 使用逆地理编码获取地址信息
                        reverseGeocode(lng, lat).then(address => {
                            // 计算与公司位置的距离
                            const distance = calculateDistance(
                                lat,
                                lng,
                                form.companyLocation.latitude,
                                form.companyLocation.longitude
                            );

                            form.locationStatus = `${address}`; // (距离公司约${Math.round(distance)}米)

                            // 判断是否在允许范围内
                            if (distance <= form.allowedRange) {
                                form.isInLocationRange = true;
                                ElMessage.success('定位成功，您在打卡范围内');
                            } else {
                                form.isInLocationRange = false;
                                ElMessage.warning(`您不在打卡范围内，需要在${form.allowedRange}米以内`);
                            }
                        });
                    } else {
                        form.locationStatus = '获取位置失败';
                        form.isInLocationRange = false;
                        ElMessage.error(`定位失败：${result.message}`);
                    }
                });
            });
        } else {
            locationLoading.value = false;
            form.locationStatus = '地图API初始化失败';
            ElMessage.error('地图API初始化失败');
        }
    };

    document.head.appendChild(script);
};

// 计算迟到或早退分钟数
const calculateMinutesDifference = (time1, time2) => {
    const [hours1, minutes1] = time1.split(':').map(Number);
    const [hours2, minutes2] = time2.split(':').map(Number);

    const totalMinutes1 = hours1 * 60 + minutes1;
    const totalMinutes2 = hours2 * 60 + minutes2;

    return totalMinutes1 - totalMinutes2;
};

// 计算打卡时间是上午还是下午
const isMorningClockIn = computed(() => {
    if (!form.clockInTime) return true;

    // 从打卡时间中提取小时分钟
    const timePart = form.clockInTime.split(' ')[1];
    if (!timePart) return true;

    const [hours] = timePart.split(':').map(Number);
    return hours < 12;
});

// 是否显示迟到分钟数（上午打卡时显示）
const showLateMinutes = computed(() => {
    return isMorningClockIn.value && form.clockInStatus === '迟到';
});

// 是否显示早退分钟数（下午打卡时显示）
const showEarlyMinutes = computed(() => {
    return !isMorningClockIn.value && form.clockInStatus === '早退';
});

// 更新表单数据
const updateFormData = () => {
    // 获取当前日期
    const now = new Date();
    const year = now.getFullYear();
    const month = String(now.getMonth() + 1).padStart(2, '0');
    const day = String(now.getDate()).padStart(2, '0');

    form.recordDate = `${year}-${month}-${day}`;

    // 计算归属考勤周期
    form.attendanceCycle = `${year}-${month}`;

    // 设置上下班时间
    form.workStartTime = `${form.recordDate} ` + form.attendanceRule.workStart;
    form.workEndTime = `${form.recordDate} ` + form.attendanceRule.workEnd;

    // 当前打卡时间
    const hours = String(now.getHours()).padStart(2, '0');
    const minutes = String(now.getMinutes()).padStart(2, '0');
    const seconds = String(now.getSeconds()).padStart(2, '0');
    form.clockInTime = `${form.recordDate} ${hours}:${minutes}:${seconds}`;

    // 判断打卡状态
    const currentTime = `${hours}:${minutes}`;
    const workStart = form.attendanceRule.workStart;
    const workEnd = form.attendanceRule.workEnd;

    // 获取容忍时间（默认为0分钟）
    const lateTolerance = form.attendanceRule.lateTolerance || 0;
    const earlyLeaveTolerance = form.attendanceRule.earlyLeaveTolerance || 0;

    console.log("上午容忍时间：" + lateTolerance);
    console.log("下午容忍时间：" + earlyLeaveTolerance);

    // 上午打卡判断迟到
    if (parseInt(hours) < 12) {
        const diffMinutes = calculateMinutesDifference(currentTime, workStart);
        if (diffMinutes > lateTolerance) {
            form.clockInStatus = '迟到';
            form.lateMinutes = `${diffMinutes}`;
        } else {
            form.clockInStatus = '正常';
            form.lateMinutes = '';
        }
        // 清空早退分钟数
        form.earlyMinutes = '';
    } else {
        // 下午打卡判断早退
        const diffMinutes = calculateMinutesDifference(workEnd, currentTime);
        if (diffMinutes > earlyLeaveTolerance) {
            form.clockInStatus = '早退';
            form.earlyMinutes = `${diffMinutes}`;
        } else {
            form.clockInStatus = '正常';
            form.earlyMinutes = '';
        }
        // 清空迟到分钟数
        form.lateMinutes = '';
    }

    // 如果当前时间超过上班时间+容忍时间或下班时间+容忍时间，则不允许打卡
    const [workStartHours, workStartMinutes] = workStart.split(':').map(Number);
    const [workEndHours, workEndMinutes] = workEnd.split(':').map(Number);

    // 计算上班时间+容忍时间
    let workStartWithTolerance = workStartHours * 60 + workStartMinutes + lateTolerance;
    let workEndWithTolerance = workEndHours * 60 + workEndMinutes + earlyLeaveTolerance;

    // 转换回小时:分钟格式
    const workStartWithToleranceHours = Math.floor(workStartWithTolerance / 60);
    const workStartWithToleranceMinutes = workStartWithTolerance % 60;
    const workStartWithToleranceStr = `${String(workStartWithToleranceHours).padStart(2, '0')}:${String(workStartWithToleranceMinutes).padStart(2, '0')}`;

    // 计算下班时间+容忍时间
    const workEndWithToleranceHours = Math.floor(workEndWithTolerance / 60);
    const workEndWithToleranceMinutes = workEndWithTolerance % 60;
    const workEndWithToleranceStr = `${String(workEndWithToleranceHours).padStart(2, '0')}:${String(workEndWithToleranceMinutes).padStart(2, '0')}`;

    // 如果当前时间超过上班时间+容忍时间或下班时间+容忍时间，则不允许打卡
    if (currentTime > workEndWithToleranceStr || currentTime < '06:00') {
        form.isClockInDisabled = true;
    }

    // 默认不在打卡范围
    form.isInLocationRange = false;
};

// 处理打卡
const handleClockIn = () => {
    if (!form.isInLocationRange) {
        ElMessage.warning('您不在打卡范围内，请获取位置并确保在公司附近');
        return;
    }

    request({
        url: "/attendanceRecord/clockIn",
        method: "post",
        params: {
            recordDate: form.recordDate,
            attendanceCycle: form.attendanceCycle,
            // workStartTime: form.workStartTime,
            // workEndTime: form.workEndTime,
            clockInTime: form.clockInTime,
            clockInStatus: form.clockInStatus,
            lateMinutes: form.lateMinutes !== '' ? parseInt(form.lateMinutes) : 0,
            earlyMinutes: form.earlyMinutes !== '' ? parseInt(form.earlyMinutes) : 0,
            locationStatus: form.locationStatus,
        }
    }).then(resp => {
        if (resp.code === 200) {
            ElMessage.success(resp.msg);
        } else {
            ElMessage.error(resp.msg);
        }
    })

};

const attendanceRule = ref({});

let loadAttendanceRules = () => {
    request({
        url: "/attendanceRule/rules",
        method: "get"
    }).then(resp => {
        // 将后端返回的数据赋值给form中的attendanceRule
        form.attendanceRule = resp.data;

        // 同时更新全局的attendanceRule变量
        attendanceRule.value = resp.data;

        // 更新表单数据
        updateFormData();
    })
};

onMounted(() => {
    // 加载考勤规则
    loadAttendanceRules();
    // getLocation();
});

const isVisible = ref(false)
// 复制添加
const add = () => {
    isVisible.value = true
    router.push('./insert.vue')
}
//修改显示
const EditDisplay = ref(false)
//编辑
const Editor = () => {
    EditDisplay.value = true
}

const open = () => {
    ElMessageBox.confirm(
        '你确定要删除吗?',
        '通知',
        {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'error',
        }
    )
        .then(() => {
            ElMessage({
                type: 'success',
                message: '删除成功',

            })
            emit("ref-table")
        })
        .catch(() => {
            ElMessage({
                type: 'warning',
                message: '取消操作',
            })
        })
}

loadAttendanceRules();
</script>

<style scoped>
/* 外层容器，可控制整体条的高度、圆角等 */
.progress-bar {
    height: 6px;
    background-color: #ccebf7;
    border-radius: 3px;
    display: flex;
    width: 100%;
    /* 确保进度条容器宽度占满父容器 */
    overflow: hidden;
    /* 防止子元素溢出 */
}

.progress {
    width: 8%;
    height: 10;
    background-color: #61c3ea;
    border-radius: 3px 0 0 3px;
    transition: width 0.3s ease;
    /* 添加宽度变化的过渡效果 */
}

.bottom-submit-bar {
    /* position: fixed; */
    /* 固定定位 */
    bottom: 0;
    /* 靠底部 */
    left: 0;
    width: 100%;
    background-color: #fff;
    /* 背景色，可根据需求调整 */
    border-top: 1px solid #eaeaea;
    /* 顶部边框，与页面区分 */
    padding: 12px 24px;
    /* 内边距，适配截图里的间距风格 */
    box-sizing: border-box;
    display: flex;
    align-items: center;
    justify-content: flex-start;
    /* 按钮靠左，可根据实际需求调整 */
    z-index: 10;
    /* 提高层级，避免被其他内容覆盖 */
}
</style>